/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hqd.ch03.v35.web.servlet.handler;

import com.hqd.ch03.utils.CollectionUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {

    private final Map<String, Object> urlMap = new LinkedHashMap<>();


    public SimpleUrlHandlerMapping() {
    }

    public SimpleUrlHandlerMapping(Map<String, ?> urlMap) {
        setUrlMap(urlMap);
    }

    public SimpleUrlHandlerMapping(Map<String, ?> urlMap, int order) {
        setUrlMap(urlMap);
        setOrder(order);
    }


    public void setMappings(Properties mappings) {
        CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap);
    }

    public Map<String, ?> getUrlMap() {
        return this.urlMap;
    }

    public void setUrlMap(Map<String, ?> urlMap) {
        this.urlMap.putAll(urlMap);
    }

    /**
     * 注册所有处理器
     *
     * @param urlMap
     */
    protected void registerHandlers(Map<String, Object> urlMap) {
        if (!urlMap.isEmpty()) {
            urlMap.forEach((url, handler) -> {
                if (!url.startsWith("/")) {
                    url = "/" + url;
                }
                // Remove whitespace from handler bean name.
                if (handler instanceof String) {
                    handler = ((String) handler).trim();
                }
                registerHandler(url, handler);
            });
        }
    }
}
